<?php
namespace app\api\service;
use think\Env;
class GongzonghaoService{

    //https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/qrcode-link/qr-code/getQRCode.html
    //https://blog.csdn.net/qq_39870660/article/details/129441645
    public function get_weixin_token()
    {
        $weixin_cache_info =  cache('weixin_access_token_key');
        $aa = 0;
        if (!empty($weixin_cache_info) && $weixin_cache_info['expire_time'] > time()) {
            return dataReturn(0,'ok',['weixin_access_token'=>$weixin_cache_info['weixin_access_token']]);
        } else {
            $configs = getConfByType('basic');
            $appid = $configs['miniapp_app_id'];
            $secret = $configs['miniapp_app_secret'];

            if (empty($appid) || empty($secret)) {
                trace_log("公众号的appid及appsecret未填写",'weixin_token_error');
               return dataReturn(-1,'公众号的appid及appsecret未填写');
            }
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$secret}";
            $content = curlGet($url);

            if (empty($content)) {
                trace_log("微信授权失败获取accessToken！",'weixin_token_error');
                return dataReturn(-1,'微信授权失败获取accessToken');
            }
            if (! is_array($content)) {
                trace_log("微信授权失败获取accessToken！".$content,'weixin_token_error');
                return dataReturn(-1,'微信授权失败,,获取accessToken');
            }
            if (empty($content['access_token']) || empty($content['expires_in'])) {
                trace_log("微信授权失败获取accessToken解析失败！".$content,'weixin_token_error');
                return dataReturn(-1,'微信授权失败获取accessToken解析失败');
            }
            /**
             * {
            "access_token": "NU7Kr6v9L9TQaqm5NE3OTPctTZx797Wxw4Snd2WL2HHBqLCiXlDVOw2l-Se0I-WmOLLniAYLAwzhbYhXNjbLc_KAA092cxkmpj5FpuqNO0IL7bB0Exz5s5qC9Umypy-rz2y441W9qgfnmNtIZWSjSQ",
            "expires_in": 7200
            }
             */
            $record = array();
            $record['weixin_access_token'] = $content['access_token'];
            $record['expire_time'] = time() + $content['expires_in'];
            $record['modifytime'] = time();
            cache('weixin_access_token_key',$record,$content['expires_in']);
           return dataReturn(0,'ok',['weixin_access_token'=>$content['access_token']]);
        }
    }
    public function getQrcodeByWechat($access_token,$user_id,$save_qrcode_image){
        $domain =  Env::get('app.HOST_URL', '');
        if(file_exists($save_qrcode_image)){
            unlink($save_qrcode_image);
        }
        $url = 'https://api.weixin.qq.com/wxa/getwxacode?access_token=' . $access_token;
        $data = [];
        $data['path'] = "pages/index/index?share_code=" . aes_encryption_encode($user_id);
//        $data['scene'] = 'type=qrcode';//(string类型,必须是数字)
        $data['width'] = 280;//二维码宽度 默认值为430，最小 280px，
        $data['env_version'] = 'trial';//正式版为 "release"，体验版为 "trial"，开发版为 "develop"。默认是正式版
        try{
            $qrcode_result = $this->curlPost($url,$data,'POST');
            if(strpos($qrcode_result,'rrcode')){
                $errArr = json_decode($qrcode_result,true);
                return dataReturn(-1,$errArr['errmsg']);
            }
            file_put_contents($save_qrcode_image,$qrcode_result);
            if(!file_exists($save_qrcode_image)){
                trace_log("图片写入文件失败".json_encode($qrcode_result),'weixin_qrcode_error');
                return dataReturn(-1,'二维码生成失败啦');
            }
            @chmod($save_qrcode_image,0777);
            //转为在线地址图片
            $qrcode_url = str_replace(ROOT_PATH."public",$domain,$save_qrcode_image);
            return dataReturn(0,'ok',['qrcode_url'=>$qrcode_url,'qrcode_path'=>$save_qrcode_image]);
        }catch (\Exception $e){
            $error = $e->getMessage();
            trace_log("获取二维码失败".$error,'weixin_qrcode_error');
            return dataReturn(-1,$error);
        }

    }
    /**
     * @param $backgroundImagePath
     * @param $logoImagePath  png
     */
    public function mergeImage($backgroundImagePath,$logoImagePath,$newImagePath){
        if(file_exists($newImagePath)){
            unlink($newImagePath);
        }
        // 获取图片信息
        list($width, $height, $type) = getimagesize($backgroundImagePath);
        list($width2, $height2, $type2) = getimagesize($logoImagePath);
        // 加载背景图和logo图
        switch ($type) {
            case IMAGETYPE_JPEG:
                $backgroundImage = imagecreatefromjpeg($backgroundImagePath);
                break;
            case IMAGETYPE_PNG:
                $backgroundImage = imagecreatefrompng($backgroundImagePath);
                break;
            case IMAGETYPE_GIF:
                $backgroundImage = imagecreatefromgif($backgroundImagePath);
                break;
            default:
                return false; // 不支持的图片类型
        }

        switch ($type2) {
            case IMAGETYPE_JPEG:
                $logoImage = imagecreatefromjpeg($logoImagePath);
                break;
            case IMAGETYPE_PNG:
                $logoImage = imagecreatefrompng($logoImagePath);
                break;
            case IMAGETYPE_GIF:
                $logoImage = imagecreatefromgif($logoImagePath);
                break;
            default:
                return false; // 不支持的图片类型
        }
//        $logoImage = imagecreatefrompng($logoImagePath);

        // 获取logo图片的宽高
        $logoWidth = imagesx($logoImage);
        $logoHeight = imagesy($logoImage);

        // 获取背景图的宽高
        $backgroundWidth = imagesx($backgroundImage);
        $backgroundHeight = imagesy($backgroundImage);

        // 计算合成位置，这里我们将logo放在背景图的右下角
        $dis_width = 140;
        $dis_height = 140;
        $x = $backgroundWidth/2 - $dis_width/2+3; // 定义新图像中内容绘制的起点位置
        $y = $backgroundHeight/2 + 12; // 定义新图像中内容绘制的起点位置

        // 将logo合成到背景图上
//        imagecopy($backgroundImage, $logoImage, $x, $y, 0, 0, $logoWidth, $logoHeight);
        imagecopyresampled($backgroundImage, $logoImage, $x, $y, 0, 0, $dis_width, $dis_height, $logoWidth, $logoHeight);
        imagepng($backgroundImage,$newImagePath);


        // 清理内存
        imagedestroy($backgroundImage);
        imagedestroy($logoImage);
        return $newImagePath;
    }
    public function curlPost($url,$data,$method){
        $headers = array(
            'Content-Type: application/json;charset=utf-8',
            'Accept: application/json',
            'Accept-Encoding: gzip, deflate'
        );

        $ch = curl_init();   //1.初始化
        curl_setopt($ch, CURLOPT_URL, $url); //2.请求地址
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);//3.请求方式
        //4.参数如下
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);//https
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');//模拟浏览器
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
        curl_setopt($ch, CURLOPT_ENCODING, 'gzip,deflate');
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

        if($method=="POST"){//5.post方式的时候添加数据
            $data = json_encode($data);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $tmpInfo = curl_exec($ch);//6.执行

        if (curl_errno($ch)) {//7.如果出错
            return curl_error($ch);
        }
        curl_close($ch);//8.关闭
        return $tmpInfo;
    }
}
